import { defineStore } from 'pinia';
import { get } from '@/utils/request';

// 应用数据管理
export const useAppStore = defineStore('app', () => {
  // 菜单数据
  const menus = ref<any[]>([]);
  
  // 权限数据
  const permissions = ref<any[]>([]);
  
  // 字典数据
  const dicts = ref<any[]>([]);
  
  // 智能体数据
  const agents = ref<any[]>([]);

  // 设置菜单
  const setMenus = (menuData: any[]) => {
    menus.value = menuData;
  };

  // 设置权限
  const setPermissions = (permissionData: any[]) => {
    permissions.value = permissionData;
  };

  // 设置字典
  const setDicts = (dictData: any[]) => {
    dicts.value = dictData;
  };

  // 设置智能体
  const setAgents = (agentData: any[]) => {
    agents.value = agentData;
  };

  // 初始化应用数据
  const initApp = async (userInfo: any) => {
    try {
      const results = await Promise.all([
        get("/sys/menu/nav"), // 加载菜单
        get("/sys/menu/permissions"), // 加载权限
        get("/sys/dict/type/all"), // 加载字典
        get("/intelligent/base/page") // 加载智能体
      ]);

      const [menusRes, permissionsRes, dictsRes, agentsRes] = results;

      // 更新 store 数据
      setPermissions(permissionsRes.data || []);
      setDicts(dictsRes.data || []);
      setMenus(menusRes.data || []);
      
      // 处理智能体数据，添加用户信息
      const processedAgents = agentsRes.data?.list?.map((item: any) => ({
        ...item,
        api_key: item.keyStr,
        url: item.addr,
        user: userInfo?.username || "admin"
      })) || [];
      
      setAgents(processedAgents);

      console.log('应用数据初始化成功');
      return true;
    } catch (error) {
      console.error('初始化应用数据错误', error);
      return false;
    }
  };

  // 清空应用数据
  const clearAppData = () => {
    menus.value = [];
    permissions.value = [];
    dicts.value = [];
    agents.value = [];
  };

  return {
    menus,
    permissions,
    dicts,
    agents,
    setMenus,
    setPermissions,
    setDicts,
    setAgents,
    initApp,
    clearAppData,
  };
}, {
  persist: true,
});